﻿/* Copyright (C) 2012 by John Cronin
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:

 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.

 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SQLite;

namespace davserv.auth.sqlite
{
    class sqlite : davserv.Auth.IAuthProvider
    {
        internal SQLiteConnection conn = null;
        string prev_init_string = null;

        public string GetHA1Hash(string username, string realm)
        {
            if (conn == null)
                throw new Exception("Please call Init() first");

            string create_table = "CREATE TABLE IF NOT EXISTS passwd (username TEXT, realm TEXT, groups TEXT, ha1 TEXT)";
            SQLiteCommand comm = conn.CreateCommand();
            comm.CommandText = create_table;
            comm.ExecuteNonQuery();

            string select_string = "SELECT ha1 FROM passwd WHERE username IS \'{0}\' AND realm IS \'{1}\'";
            select_string = string.Format(select_string, username, realm);
            comm = conn.CreateCommand();
            comm.CommandText = select_string;
            SQLiteDataReader dr = comm.ExecuteReader();

            if (!dr.HasRows)
                return null;
            dr.Read();
            return dr.GetString(0);
        }

        public void Init(string init_string)
        {
            if ((init_string != null) && (init_string != prev_init_string))
            {
                string[] lines = init_string.Split(',');
                Dictionary<string, string> args = new Dictionary<string, string>();
                foreach (string line in lines)
                {
                    string[] opts = line.Split('=');
                    args[opts[0].Trim()] = opts[1].Trim();
                }

                if (conn != null)
                    conn.Close();
                conn = new SQLiteConnection(String.Format("Data Source={0};", args["file"]));
                conn.Open();
                prev_init_string = init_string;
            }
        }

        public string[] GetGroups(string username, string realm)
        {
            if(conn == null)
                throw new Exception("Please call Init() first");

            string select_string = "SELECT groups FROM passwd WHERE username IS \'{0}\' AND realm IS \'{1}\'";
            select_string = string.Format(select_string, username, realm);
            SQLiteCommand comm = conn.CreateCommand();
            comm.CommandText = select_string;
            SQLiteDataReader dr = comm.ExecuteReader();

            if (!dr.HasRows)
                return null;

            dr.Read();
            string groups = dr.GetString(0);
            return groups.Split(',');
        }


        public bool SetPassword(string username, string realm, string old_pass, string new_pass)
        {
            if(conn == null)
                throw new Exception("Please call Init() first");

            // First check the old password
            string select_string = "SELECT ha1 FROM passwd WHERE username IS \'{0}\' AND realm IS \'{1}\'";
            select_string = string.Format(select_string, username, realm);
            SQLiteCommand comm = conn.CreateCommand();
            comm.CommandText = select_string;
            SQLiteDataReader dr = comm.ExecuteReader();

            // Generate hash of new password
            string new_ha1 = Auth.ComputeMD5Hash(username + ":" + realm + ":" + new_pass);

            // User exists, therefore check old password and update
            if (dr.HasRows)
            {
                dr.Read();
                string old_ha1 = dr.GetString(0);
                if (!Auth.VerifyMD5Hash(username + ":" + realm + ":" + old_pass, old_ha1))
                    return false;

                string update_string = "UPDATE passwd SET ha1 = \'{0}\' WHERE username IS \'{1}\' AND realm IS \'{2}\'";
                update_string = string.Format(update_string, new_ha1, username, realm);
                comm = conn.CreateCommand();
                comm.CommandText = update_string;
                if (comm.ExecuteNonQuery() == 1)
                    return true;
                return false;
            }
            else
            {
                // Need to add a new user
                string insert_string = "INSERT INTO passwd VALUES (\'{0}\', \'{1}\', \'{2}\', \'{3}\')";
                insert_string = string.Format(insert_string, username, realm, "", new_ha1);
                comm = conn.CreateCommand();
                comm.CommandText = insert_string;
                if (comm.ExecuteNonQuery() == 1)
                    return true;
                return false;
            }
        }

        public bool SetGroups(string username, string realm, string[] groups)
        {
            throw new NotImplementedException();
        }

        public bool DeleteUser(string username, string realm)
        {
            throw new NotImplementedException();
        }
    }
}
